package com.zyx.javademo.juc.scheduled;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.time.LocalDateTime;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Yaxi.Zhang
 * @since 2021/6/10 10:21
 * desc:
 */
public class ScheThrPoolDemo {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        // new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    // 系统睡5s钟, 而 ScheduledExecutorService 中指定每隔 2s 执行一次
                    // 观察 2s 后还是 5s 后执行输出语句
                    Thread.sleep(5000);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                // System.out.println(Thread.currentThread().getName()+" run: "+ System.currentTimeMillis());
                System.out.println("name: " + Thread.currentThread().getName()+", run time : " + LocalDateTime.now());
            }
        }, 0, 2, TimeUnit.SECONDS);
    }
}
